package com.gglx
{
	import com.gglx.app.clip.dto.LocalData;
	import com.gglx.mobile.extenstions.GGPushNotification;

	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.Dictionary;

	import pl.mateuszmackowiak.nativeANE.properties.SystemProperties;

	public class LocalAppData
	{
		public static var CONFIG:LocalData;

		private static var inited:Boolean=false;
		private static var file:File;
		private static var fileStream:FileStream;

		private static var _completeCallBack:Function;

		public static function initData(completeCallBack:Function=null):void
		{
			if (!inited)
			{
				inited=true;

				if (SystemProperties.isSupported)
				{
					var systemProperties:Dictionary=SystemProperties.getInstance().getSystemProperites();

					if (systemProperties["UID"])
					{
						GlobalRegister.CUID=systemProperties["UID"];
					}

					GlobalRegister.SYSTEM_PROPERTIES="model:"+systemProperties["model"]+"|name:"+systemProperties["name"]+"|os:"+systemProperties["os"]+"|version:"+systemProperties["version"]+"|IMEI:"+systemProperties["IMEI"]+"|IMSI:"+systemProperties["IMSI"]+"|"+systemProperties["TMH"];

					trace(GlobalRegister.SYSTEM_PROPERTIES);
				}

				_completeCallBack=completeCallBack;

				CONFIG=new LocalData();

				file=File.applicationStorageDirectory.resolvePath("configs/gg.cfg");
				fileStream=new FileStream();
				fileStream.addEventListener(Event.COMPLETE, completeHandler);
				fileStream.addEventListener(IOErrorEvent.IO_ERROR, iOErrorHandler); // lỗi khi mở file

				readFile();
			}
		}

		private static function completeHandler(event:Event):void
		{
			CONFIG.loadData(JSON.parse(fileStream.readMultiByte(fileStream.bytesAvailable, "utf-8")));

			loadFileComplete();
		}

		private static function readFile():void
		{
			fileStream.openAsync(file, FileMode.READ);

			trace(file.nativePath);
		}

		private static function iOErrorHandler(event:IOErrorEvent):void
		{
			writeFile();

			loadFileComplete();
		}

		public static function writeFile():void
		{
			fileStream.openAsync(file, FileMode.WRITE);

			fileStream.writeMultiByte(JSON.stringify(CONFIG), "utf-8");
		}

		public static function loadFileComplete():void
		{
			/*
			Nếu chưa đăng ký nhận push
			*/
			if (!CONFIG.isRegistered)
			{
				GGPushNotification.init();
			}

			if (_completeCallBack != null)
			{
				_completeCallBack.call();
			}
		}
	}
}
